<template>
  <div class="commission-report">
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <!-- 佣金统计 -->
      <el-tab-pane label="佣金统计" name="commission">
        <!-- 第一行：佣金金额统计 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-value">¥{{ commissionData.total_amount || 0 }}</div>
                <div class="stat-label">总佣金
                  <el-tooltip placement="top">
                    <div slot="content" style="max-width: 460px; line-height: 1.5;">
                      <div><strong>定义：</strong>查询时间范围内"产生的佣金总金额"</div>
                      <div><strong>计算：</strong>SUM(佣金金额)</div>
                      <div><strong>来源：</strong><code>consul_nfc_commission_records</code>（已结算+待结算均计入）</div>
                      <div><strong>筛选：</strong>受时间范围 / 商户筛选限制</div>
                      <div><strong>示例：</strong>佣金记录 120、80、50 → 总佣金 = 250</div>
                    </div>
                    <i class="el-icon-question" style="margin-left:6px;color:#909399;"></i>
                  </el-tooltip>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-value">¥{{ commissionData.settled_amount || 0 }}</div>
                <div class="stat-label">已结算
                  <el-tooltip placement="top">
                    <div slot="content" style="max-width: 460px; line-height: 1.5;">
                      <div><strong>定义：</strong>查询时间范围内"已完成结算"的佣金金额</div>
                      <div><strong>计算：</strong>SUM(佣金金额，条件 settlement_status=已结算)</div>
                      <div><strong>来源：</strong><code>consul_nfc_commission_records</code></div>
                      <div><strong>提示：</strong>与"待结算"合计应接近"总佣金"（口径差异以后端为准）</div>
                    </div>
                    <i class="el-icon-question" style="margin-left:6px;color:#909399;"></i>
                  </el-tooltip>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-value">¥{{ commissionData.pending_amount || 0 }}</div>
                <div class="stat-label">待结算
                  <el-tooltip placement="top">
                    <div slot="content" style="max-width: 460px; line-height: 1.5;">
                      <div><strong>定义：</strong>查询时间范围内"尚未结算"的佣金金额</div>
                      <div><strong>计算：</strong>SUM(佣金金额，条件 settlement_status=待结算)</div>
                      <div><strong>来源：</strong><code>consul_nfc_commission_records</code></div>
                      <div><strong>提示：</strong>可与"已结算"一起用于评估结算进度</div>
                    </div>
                    <i class="el-icon-question" style="margin-left:6px;color:#909399;"></i>
                  </el-tooltip>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 第二行：佣金笔数统计 -->
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-value">{{ commissionData.total_count || 0 }}</div>
                <div class="stat-label">总笔数
                  <el-tooltip placement="top">
                    <div slot="content" style="max-width: 420px; line-height: 1.5;">
                      <div><strong>定义：</strong>查询时间范围内佣金交易的总笔数</div>
                      <div><strong>计算：</strong>COUNT(佣金记录)</div>
                      <div><strong>来源：</strong><code>consul_nfc_commission_records</code></div>
                      <div><strong>示例：</strong>本期产生 120 条佣金记录 → 总笔数 = 120</div>
                    </div>
                    <i class="el-icon-question" style="margin-left:6px;color:#909399;"></i>
                  </el-tooltip>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-value">{{ commissionData.settled_count || 0 }}</div>
                <div class="stat-label">已结算笔数
                  <el-tooltip placement="top">
                    <div slot="content" style="max-width: 420px; line-height: 1.5;">
                      <div><strong>定义：</strong>查询时间范围内处于"已结算"状态的佣金记录笔数</div>
                      <div><strong>计算：</strong>COUNT(佣金记录，条件 settlement_status=已结算)</div>
                      <div><strong>来源：</strong><code>consul_nfc_commission_records</code></div>
                    </div>
                    <i class="el-icon-question" style="margin-left:6px;color:#909399;"></i>
                  </el-tooltip>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-value">{{ commissionData.pending_count || 0 }}</div>
                <div class="stat-label">待结算笔数
                  <el-tooltip placement="top">
                    <div slot="content" style="max-width: 420px; line-height: 1.5;">
                      <div><strong>定义：</strong>查询时间范围内处于"待结算"状态的佣金记录笔数</div>
                      <div><strong>计算：</strong>COUNT(佣金记录，条件 settlement_status=待结算)</div>
                      <div><strong>来源：</strong><code>consul_nfc_commission_records</code></div>
                    </div>
                    <i class="el-icon-question" style="margin-left:6px;color:#909399;"></i>
                  </el-tooltip>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 第三行：分析指标 -->
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-value">¥{{ commissionData.avg_amount || 0 }}</div>
                <div class="stat-label">平均佣金
                  <el-tooltip placement="top">
                    <div slot="content" style="max-width: 420px; line-height: 1.5;">
                      <div><strong>定义：</strong>每笔佣金的平均金额</div>
                      <div><strong>计算：</strong>总金额 ÷ 总笔数</div>
                      <div><strong>示例：</strong>总金额 2500 元、总笔数 100 笔 → 平均佣金 = 25 元/笔</div>
                    </div>
                    <i class="el-icon-question" style="margin-left:6px;color:#909399;"></i>
                  </el-tooltip>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-value">¥{{ commissionData.max_amount || 0 }}</div>
                <div class="stat-label">最高佣金
                  <el-tooltip placement="top">
                    <div slot="content" style="max-width: 420px; line-height: 1.5;">
                      <div><strong>定义：</strong>单笔佣金中的最高金额</div>
                      <div><strong>计算：</strong>MAX(单笔佣金金额)</div>
                    </div>
                    <i class="el-icon-question" style="margin-left:6px;color:#909399;"></i>
                  </el-tooltip>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-value">¥{{ commissionData.min_amount || 0 }}</div>
                <div class="stat-label">最低佣金
                  <el-tooltip placement="top">
                    <div slot="content" style="max-width: 420px; line-height: 1.5;">
                      <div><strong>定义：</strong>单笔佣金中的最低金额</div>
                      <div><strong>计算：</strong>MIN(单笔佣金金额)</div>
                    </div>
                    <i class="el-icon-question" style="margin-left:6px;color:#909399;"></i>
                  </el-tooltip>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 图表区域 -->
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="12">
            <el-card>
              <div slot="header">佣金趋势
                <el-tooltip placement="top">
                  <div slot="content" style="max-width: 480px; line-height: 1.5;">
                    <div><strong>定义：</strong>按日统计佣金变动趋势</div>
                    <div><strong>Y 轴：</strong>佣金金额（元）</div>
                    <div><strong>X 轴：</strong>日期</div>
                    <div><strong>来源：</strong>后端聚合（按日汇总）</div>
                  </div>
                  <i class="el-icon-question" style="margin-left:6px;color:#909399;"></i>
                </el-tooltip>
              </div>
              <div id="commissionTrendChart" style="height: 350px;"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card>
              <div slot="header">商户佣金排行
                <el-tooltip placement="top">
                  <div slot="content" style="max-width: 460px; line-height: 1.5;">
                    <div><strong>定义：</strong>按商户汇总的佣金金额排行</div>
                    <div><strong>Y 轴：</strong>商户名称</div>
                    <div><strong>X 轴：</strong>佣金金额（元）</div>
                    <div><strong>来源：</strong>后端聚合（按商户汇总）</div>
                    <div><strong>筛选：</strong>受时间范围 / 商户筛选限制</div>
                  </div>
                  <i class="el-icon-question" style="margin-left:6px;color:#909399;"></i>
                </el-tooltip>
              </div>
              <div id="merchantCommissionChart" style="height: 350px;"></div>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- 结算明细 -->
      <el-tab-pane label="结算明细" name="settlement">
        <el-table
          :data="commissionSettlementData"
          border
          stripe
          v-loading="settlementLoading"
          :header-cell-style="{ background: '#f5f7fa' }"
          height="500px"
          style="width: 100%;">
          <el-table-column
            v-for="col in commissionSettlementColumns"
            :key="col.prop"
            :prop="col.prop"
            :label="col.label"
            :min-width="col.minWidth"
            align="center"
          />
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { nfcReportsAPI } from '@/api/nfc'
import ChartMixin from '../mixins/ChartMixin'

export default {
  name: 'CommissionReport',
  mixins: [ChartMixin],
  props: {
    filters: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      activeTab: 'commission',
      
      // 佣金数据
      commissionData: {},
      commissionSettlementData: [],
      
      // 加载状态
      settlementLoading: false,

      // 结算明细表格列配置
      commissionSettlementColumns: [
        { prop: 'settlement_id', label: '结算ID', minWidth: 100 },
        { prop: 'merchant_name', label: '商户名称', minWidth: 180 },
        { prop: 'settlement_amount', label: '结算金额', minWidth: 120 },
        { prop: 'commission_count', label: '佣金笔数', minWidth: 100 },
        { prop: 'settlement_status', label: '结算状态', minWidth: 100 },
        { prop: 'create_time', label: '创建时间', minWidth: 160 },
        { prop: 'completed_at', label: '完成时间', minWidth: 160 }
      ]
      
    }
  },
  watch: {
    filters: {
      handler() {
        this.loadCurrentTabData()
      },
      deep: true
    }
  },
  mounted() {
    this.loadCurrentTabData()
  },
  methods: {

    // 标签页切换
    async handleTabClick() {
      await this.loadCurrentTabData()
    },

    // 根据当前标签页加载数据
    async loadCurrentTabData() {
      try {
        if (this.activeTab === 'commission') {
          await this.loadCommissionData()
        } else if (this.activeTab === 'settlement') {
          await this.loadCommissionSettlementData()
        }
      } catch (error) {
        console.error('加载佣金报表数据失败：', error)
        this.$message.error('加载数据失败')
      }
    },

    // 加载佣金数据
    async loadCommissionData() {
      const params = { ...this.filters }
      const response = await nfcReportsAPI.getCommissionReport(params)
      const data = response.data || {}

      // 提取overview数据（包含所有统计字段）
      const overview = data.overview || data.stats || {}

      // 映射所有返回的数据字段
      this.commissionData = {
        // 金额统计
        total_amount: overview.total_amount || 0,
        settled_amount: overview.settled_amount || 0,
        pending_amount: overview.pending_amount || 0,

        // 笔数统计
        total_count: overview.total_count || 0,
        settled_count: overview.settled_count || 0,
        pending_count: overview.pending_count || 0,

        // 分析指标
        avg_amount: overview.avg_amount || 0,
        max_amount: overview.max_amount || 0,
        min_amount: overview.min_amount || 0,

        // 统计周期
        period: data.period || 'unknown'
      }

      this.$nextTick(() => {
        this.renderCommissionCharts(data)
      })
    },

    // 加载结算明细数据
    async loadCommissionSettlementData() {
      try {
        this.settlementLoading = true
        const params = {
          ...this.filters,
          report_type: 'settlement'
        }
        const res = await nfcReportsAPI.getCommissionReport(params)
        console.log('结算明细响应:', res)
        if (res && res.code === 0 && res.data && res.data.settlement_data) {
          this.commissionSettlementData = res.data.settlement_data
        } else {
          this.commissionSettlementData = []
        }
      } catch (error) {
        console.error('加载结算明细失败:', error)
        this.$message.error('加载结算明细失败')
        this.commissionSettlementData = []
      } finally {
        this.settlementLoading = false
      }
    },

    // 渲染佣金图表
    renderCommissionCharts(data) {
      // 佣金趋势
      this.renderChart('commissionTrendChart', {
        title: { text: '' },
        xAxis: { 
          type: 'category', 
          data: data.trend_dates || [] 
        },
        yAxis: { type: 'value' },
        series: [{
          name: '佣金金额',
          data: data.trend_values || [],
          type: 'line',
          smooth: true,
          areaStyle: {},
          itemStyle: { color: '#67C23A' }
        }]
      })

      // 商户佣金排行
      this.renderChart('merchantCommissionChart', {
        title: { text: '' },
        xAxis: { type: 'value' },
        yAxis: { type: 'category', data: data.merchant_names || [] },
        series: [{
          data: data.merchant_commissions || [],
          type: 'bar',
          itemStyle: { color: '#909399' }
        }]
      })
    },

    // 格式化金额显示
    formatAmount(amount) {
      const num = Number(amount || 0)
      return num.toFixed(2)
    }

  }
}
</script>

<style scoped>
.commission-report {
  padding: 0;
}

.stat-card {
  height: 120px;
}

.stat-content {
  text-align: center;
  padding: 20px 0;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #67C23A;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.commission-report .el-table {
  width: 100% !important;
}

.commission-report .el-tabs__content {
  padding-left: 0;
  padding-right: 0;
}
</style>